package com.eascs.finance.admin.web.service;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.app.context.ConfigContext;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertInfoUtils;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.ftp.FtpConfig;
import com.eascs.common.ftp.FtpHelper;
import com.eascs.common.util.UuidUtil;
import com.eascs.finance.admin.common.entity.Attachment;
import com.eascs.finance.admin.server.manager.IAttachmentManager;

@Service
public class AttachmentService  {
	private Logger logger = LoggerFactory.getLogger(AttachmentService.class);
	@Inject
	IAttachmentManager attachmentManager;

	@Inject
	private FtpConfig ftpConfig;
	public static final String FILE_NAME_BLOB_PASTE = "_blob_paste";
	public static final DateFormat FILE_NAME_DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
	public static final DateFormat FILE_PATH_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");



	public Attachment uploadAttachment(MultipartFile file) {
		String id = UuidUtil.generateShortUuid(2);
		String fileName = file.getOriginalFilename();
		if (fileName.startsWith(FILE_NAME_BLOB_PASTE)) {
			fileName = "粘贴截图" + FILE_NAME_DATE_FORMAT.format(new Date()) + "_" + UuidUtil.generateUuid8WithMd5() + fileName.substring(FILE_NAME_BLOB_PASTE.length());
		}
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		// String name = fileName.substring(0, fileName.lastIndexOf("."));
		String filePath = buildFilePath(id, suffix);

		Attachment attachment = new Attachment();
		attachment.setName(fileName);
		attachment.setFilePath(filePath);
		attachment.setViewUrl("/attachment/view?id=" + id);
		attachment.setFileSize(file.getSize());
		attachment.setId(id);
		attachment.setSuffix(suffix);
		
		
		try {
			FtpHelper.upload(ftpConfig, file.getInputStream(), filePath);
			attachmentManager.addAttachment(attachment);
			logger.debug("upload to {}", filePath);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}

		
		return attachment;
	}

	private String buildFilePath(String id, String suffix) {
		return ConfigContext.getStringValue("attachment.upload.dir") + "/" + FILE_PATH_DATE_FORMAT.format(new Date()) + "/" + id + "." + suffix;
	}

	public Attachment getAttachmentById(String id) {
		Attachment attachment = attachmentManager.findAttachmentById(id);
		AssertInfoUtils.assertNotNull(attachment, "can't load attachment with id:{}", id);
		return attachment;
	}

}
